package com.chaos.auth.helper;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.AlgorithmParameters;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
 * @author yjp
 * @date 2024/5/31
 */
@Deprecated

public class AESHelper {

    public static boolean initialized = false;

    /**
     * AES解密
     * @param content 密文
     * @return
     * @throws InvalidAlgorithmParameterException
     * @throws NoSuchProviderException
     */
    public static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws Exception {
        initialize();
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");

            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void initialize(){
        if (initialized) return;
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }
    //生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception{
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }

    public static void main(String[] args) throws Exception {
        byte[] decrypt = decrypt(Base64.decodeBase64("lo1GoHjyXpn4SlVf2CmuxFvFd2tiE4k/+fAtI/mDZJhX8125vcukb85eZ8eJ3OQRs9YcbFh1sOytoKGvbH9dPzSNFpkV7ZzLdBMnnDJ0LaGAtIbZcNwtdSmWacghSVOmk/teBcWzCUpV64zdrUpyeBSdEwrvat1GvddGPxRhj46aKW2f87uXk9Xd9oZcVHAIVTSkTyu/IBIDbKZMe3Y6dw=="), Base64.decodeBase64("nSEWDyKBeK2SRRW905WXsA=="), Base64.decodeBase64("sbyAbBLIuJLbIxD/GkI6bw=="));
        String s = new String(decrypt, StandardCharsets.UTF_8);
        System.out.println(s);
    }
}
